package com.gson.inter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import com.gson.bean.Articles;
import com.gson.model.BaiduMapJSONBean;
import com.gson.model.GoogleMapJSONBean;
import com.gson.model.LocateInfoModel;
import com.gson.model.Point;
import com.gson.model.PosInfoModel;
import com.gson.util.MD5Builder;
import com.gson.util.MobileConfig;


public class LocateUtil {

	public String getMobileLocateInfo(String phoneNo) throws Exception {
		LocateInfoModel model = new LocateInfoModel();
		model.setAppKey(MobileConfig.appKey);
		model.setApiName(MobileConfig.apiName);
		model.setApiMethod(MobileConfig.apiMethod);
		model.setMobileNo(phoneNo);
		model.setTimestamp(getTimeStamp());
		
		// 生成请求xml
		String reqXml = createParmXml(model);
		
		//返回XML
		String rtnXml = "";
		//http地址
		StringBuilder requestUrl = new StringBuilder(MobileConfig.serverAddress);
		String parm = "?reqXml=" + URLEncoder.encode(reqXml, "UTF-8") + "&sign=" + MD5Builder.getMD5Str(reqXml + MobileConfig.appSecret);
		requestUrl.append(parm);
		String httpUrl = requestUrl.toString();
		System.out.println("请求URL="+httpUrl);
		rtnXml = getHttpResult(httpUrl);
		return rtnXml;
	}

    public String getTimeStamp() {
    	String timestamp = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		timestamp = sdf.format(new Date());
		return timestamp;
    }

	public String createParmXml(LocateInfoModel model) {
		StringBuffer parmXml = new StringBuffer("");
		parmXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		parmXml.append("<reqXML version=\"1.0\">");
		String appKeyParm = "<appKey>" + model.getAppKey() + "</appKey>";
		String apiNameParm = "<apiName>" + model.getApiName() + "</apiName>";
		String apiMethodParm = "<apiMethod>" + model.getApiMethod() + "</apiMethod>";
		String timestampParm = "<timestamp>" + model.getTimestamp() + "</timestamp>";
		parmXml.append(appKeyParm);
		parmXml.append(apiNameParm);
		parmXml.append(apiMethodParm);
		parmXml.append(timestampParm);
		parmXml.append("<params>");
		String mobileParm = "<param name=\"mobile\" value=\"" + model.getMobileNo() + "\"/>";
		parmXml.append(mobileParm);
		parmXml.append("</params>");
		parmXml.append("</reqXML>");
		String parmXmlStr = parmXml.toString();
		System.out.println("生成的XML=");
		System.out.println(parmXmlStr);
		return parmXmlStr;
	}

    public static void main(String args[]) {
        String phone = "18930823570";
        LocateUtil util = new LocateUtil();
        try {
            //String rtnXml = util.getMobileLocateInfo(phone);
            //System.out.println(rtnXml);
            
            //util.getAddress("31.168272,121.387072");
            System.out.println(util.getBaiduAddress("121.387072,31.168272"));
        	//System.out.println(util.getBaiduGeo("121.387072,31.168272"));
        } catch(Exception e) {
            e.printStackTrace();
        }
    	
    }
    
    public List<Articles> getBaiduMap(PosInfoModel posInfo, String content) {
    	List<Articles> articleList = new ArrayList<Articles>();
		Articles articles = new Articles();
		// 形如 31.168272,121.387072
		String latlng = posInfo.getLATITUDE() + "," + posInfo.getLONGITUDE();
		// 形如 121.387072,31.168272
		String lnglat = posInfo.getLONGITUDE() + "," + posInfo.getLATITUDE();
		String baiduGeo = getBaiduGeo(lnglat);
		StringBuilder sb = new StringBuilder();
		sb.append("http://api.map.baidu.com/staticimage?center=" +
				baiduGeo +
				"&width=640&height=320&zoom=17&markers=" +
				baiduGeo +
				"&markerStyles=l,A");
		articles.setPicUrl(sb.toString());
		articles.setTitle(content+"  大致所在位置");
		articles.setDescription(getBaiduAddress(lnglat));
		String url = "http://api.map.baidu.com/geocoder?location=" + latlng + 
				"&coord_type=wgs84&output=html";
		articles.setUrl(url);
		articleList.add(articles);
		return articleList;
    }
    
    public List<Articles> getGoogleMap(PosInfoModel posInfo, String content) {
    	List<Articles> articleList = new ArrayList<Articles>();
		Articles articles = new Articles();
		// 形如 31.168272,121.387072
		String latlng = posInfo.getLATITUDE() + "," + posInfo.getLONGITUDE();
		// 形如 121.387072,31.168272
		String lnglat = posInfo.getLONGITUDE() + "," + posInfo.getLATITUDE();
		StringBuilder sb = new StringBuilder();
		sb.append("http://maps.googleapis.com/maps/api/staticmap?center=" +
				latlng +
				"&zoom=17&size=640x320&markers=color:0xfd7a70%7Clabel:A%7C" +
				latlng +
				"&sensor=false");
		//articles.setPicUrl(sb.toString());
		articles.setTitle(content+"  大致所在位置");
		articles.setDescription(getBaiduAddress(lnglat));
		String url = "http://ditu.google.cn/maps?hl=zh-CN&mrt=loc&q=" + latlng;
		articles.setUrl(url);
		articleList.add(articles);
		return articleList;
    }
    
    public String getBaiduGeo(String lnglat) {
    	String baiduGeo = "";
    	String rtnXml = null;
    	// 百度坐标转换请求地址
    	String requestUrl = "http://api.map.baidu.com/geoconv/v1/?coords={LOCATION}&from=3&to=5&ak=mGW8G2Gfg08CuO3bZBj6Iy9i";
    	try {
    		// 对音乐名称、作者进URL编码
    		requestUrl = requestUrl.replace("{LOCATION}", urlEncodeUTF8(lnglat));
    		// 处理名称、作者中间的空格
    		requestUrl = requestUrl.replaceAll("\\+", "%20");
    		rtnXml = getHttpResult(requestUrl);
    		JSONObject jsonObject = JSONObject.fromObject( rtnXml );
    		JSONArray jsonArray = jsonObject.getJSONArray("result");
    		Point[] pointArray = (Point[]) JSONArray.toArray(jsonArray, Point.class);
    		baiduGeo = pointArray[0].getX() + "," + pointArray[0].getY();
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
		return baiduGeo;
    }
    
    public String getAddress(String latlng){
    	String address = "";
    	String rtnXml = null;
    	String httpUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+latlng+"&language=zh-CN&sensor=false";
    	try {
    		rtnXml = getHttpResult(httpUrl);
    		
    		  JSONObject jsonObject = JSONObject.fromObject( rtnXml );
    	      GoogleMapJSONBean bean = (GoogleMapJSONBean) JSONObject.toBean( jsonObject, GoogleMapJSONBean.class );
    	      address = bean.getResults()[1].formatted_address;
    	      System.out.println("address="+address);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
		return address;
    	
    }
    
    public String getBaiduAddress(String lnglat){
    	String address = "";
    	String rtnXml = null;
    	// 百度反 Geocoding地址
    	String requestUrl = "http://api.map.baidu.com/telematics/v3/reverseGeocoding?location={LOCATION}&coord_type=wgs84&ak=mGW8G2Gfg08CuO3bZBj6Iy9i&output=json";
    	try {
    		// 对音乐名称、作者进URL编码
    		requestUrl = requestUrl.replace("{LOCATION}", urlEncodeUTF8(lnglat));
    		// 处理名称、作者中间的空格
    		requestUrl = requestUrl.replaceAll("\\+", "%20");
    		rtnXml = getHttpResult(requestUrl);
    		JSONObject jsonObject = JSONObject.fromObject( rtnXml );
    		BaiduMapJSONBean bean = (BaiduMapJSONBean) JSONObject.toBean( jsonObject, BaiduMapJSONBean.class );
    	      address = bean.getDescription();
    	      System.out.println("address="+address);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
		return address;
    }

	/**
	 * @param httpUrl
	 * @return 
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	private String getHttpResult(String httpUrl) throws Exception {
		String rtnXml = null;
		//HttpGet连接对象
		HttpGet httpRequest = new HttpGet(httpUrl);  
		//取得HttpClient对象  
		HttpClient httpclient = new DefaultHttpClient(); 
		//设置连接超时
		httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,50000);
		//设置读取超时
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,10000);
		//请求HttpClient，取得HttpResponse  
			HttpResponse httpResponse = httpclient.execute(httpRequest); 
			//请求成功  
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				//取得返回的字符串  
				rtnXml = EntityUtils.toString(httpResponse.getEntity()).trim(); 
				System.out.println(rtnXml);
			}
			return rtnXml;
	}
    
    
	/**
	 * UTF-8编码
	 * 
	 * @param source
	 * @return
	 */
	private static String urlEncodeUTF8(String source) {
		String result = source;
		try {
			result = java.net.URLEncoder.encode(source, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}
    
}